package com.wm.android.mydemos.activities.viewpager;

import com.wm.android.mydemos.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class FragmentPagerWithActionBar extends FragmentActivity implements TabListener {
	
	ActionBar mBar;

	@Override
	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		setContentView(R.layout.singleviewpager);

		ViewPager mPager = (ViewPager) findViewById(R.id.singleviewpager_viewpager);

		mBar = getActionBar();
		mBar.setDisplayHomeAsUpEnabled(true);
		mBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		MyAdapter mAdapter = new MyAdapter(getSupportFragmentManager());
		mPager.setAdapter(mAdapter);
		mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				
				mBar.setSelectedNavigationItem(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		for (int i = 0; i < 2; i++) {
			Tab mTab = mBar.newTab();
			mTab.setText(String.valueOf(i)).setTabListener(this);
			mBar.addTab(mTab);
		}
	}

	class MyAdapter extends FragmentPagerAdapter {

		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int arg0) {
			
			int source = 0;
			
			switch (arg0) {
			case 0:
				source = R.drawable.block_black;
				break;

			case 1:
				source = R.drawable.block_red;
				break;
			}
			Fragment mFragment = new SimpleFragment(source);
			return mFragment;
		}

		@Override
		public int getCount() {

			return 2;
		}

	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {

	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

	}
}

class SimpleFragment extends Fragment {
	
	public int mImageSource;
	
	public SimpleFragment(int i){
		
		this.mImageSource = i;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		ImageView mView = (ImageView) inflater.inflate(R.layout.item_imageview, container, false);
		mView.setImageResource(mImageSource);
		return mView;
	}
}
